package com.tmsps.common.util;

import com.tmsps.common.annotation.DeleteStatus;
import com.tmsps.ne4spring.orm.ClassUtil;
import com.tmsps.ne4spring.orm.model.DataModel;
import com.tmsps.ne4spring.utils.ChkUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author jiangtao
 */
public class AppClassUtil extends ClassUtil {

    /**
     * 设置实体数据为删除状态
     * @param model 数据
     */
    public static void setDeleteStatus(DataModel model) {
        Field deleteField = getDeleteField(model);

        // 设置字段为删除状态
        int deleteStatus = getDeleteFieldVal(deleteField);
        AppClassUtil.setClassVal(deleteField, model, deleteStatus);

    }

    /**
     * 获取父类的泛型类型
     * @param clazz 当前对象类型
     * @return 泛型类型
     */
    public static Type[] getSupperClassActualType(Class<?> clazz){
        Type superclass = clazz.getGenericSuperclass();
        if (superclass instanceof Class) {
            return null;
        } else {
            ParameterizedType parameterized = (ParameterizedType)superclass;
            return parameterized.getActualTypeArguments();
        }
    }

    /**
     * 获取数据的删除字段
     *
     * @param model 数据
     * @return 返回删除字段
     */
    public static Field getDeleteField(DataModel model) {
        Class clazz = model.getClass();
        Field deleteField = null;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent((Class<? extends Annotation>) DeleteStatus.class)) {
                deleteField = field;
                break;
            }
        }

        if(ChkUtil.isNull(deleteField)){
            throw new RuntimeException("删除字段没有正确设置DeleteStatus注解");
        }

        return deleteField;
    }

    /**
     * 获取删除字段的注解值
     * @param deleteField 被DeleteStatus标注的字段
     * @return 返回注解的值
     */
    public static int getDeleteFieldVal(Field deleteField) {
        if(ChkUtil.isNull(deleteField)){
            throw new IllegalArgumentException("参数不能为空");
        }
        DeleteStatus annotation = deleteField.getAnnotation(DeleteStatus.class);
        if(ChkUtil.isNull(annotation)){
            throw new RuntimeException("删除字段没有正确设置DeleteStatus注解");
        }
        return annotation.value();
    }

}
